package com.scpii.api.common.auth;

import javax.annotation.Resource;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import com.scpii.api.common.auth.client.ClientDetailsService;
import com.scpii.api.common.auth.token.ResourceServerTokenServices;
import com.scpii.api.common.exception.InvalidTokenException;

@Component
public class ResourceAuthenticationManager implements AuthenticationManager {

	@Resource(name = "defaultTokenServices")
	private ResourceServerTokenServices tokenServices;

	@Resource(name = "defaultClientDetailsService")
	private ClientDetailsService clientDetailsService;

	@Override
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		String token = (String) authentication.getPrincipal();
		ClientAuthentication auth = tokenServices.loadAuthentication(token);
		if (auth == null) {
			throw new InvalidTokenException("Invalid token: " + token);
		}
		auth.setDetails(authentication.getDetails());
		clientDetailsService.updateLastActivityDt(auth);
		return auth;
	}

}
